package com.example.sxproject.controller;

import com.example.sxproject.pojo.*;
import com.example.sxproject.service.LoanService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Controller
@RequestMapping("/loan")
@Validated
public class LoanController {

    @Autowired
    private LoanService loanService;

    //查询select：查询全部(包括假删除后)
    @GetMapping("/loanProduct")
    public Result getAll() {
        List<LoanProduct> products = loanService.SelectAll();
        return Result.success(products);
    }

    //查询select：根据用户id查询
    @GetMapping("/loanProductByUserId")
    public Result getProductsByUserId(Integer userId) {
        List<LoanProduct> products = loanService.SelectByUserId(userId);
        return Result.success(products);
    }

    //添加insert：新增一个贷款产品
    @PostMapping("/insertLoan")
    public Result addLoanProduct(@RequestBody LoanProduct loanProduct) {
        loanService.addLoanProduct(loanProduct);
        return Result.success();
    }

    //添加insert：添加一个用户-产品
    @PostMapping("/insertUP")
    public String addUserAndLoan(LoanUser loanUser, HttpSession session, Integer timeContinue) {

        User user = (User) session.getAttribute("user");
        loanUser.setUserId(user.getId());//设置所属用户

        //获取当前时间
        LocalDateTime dateTime = LocalDateTime.now();
        LocalDateTime dateTimePlusOneMonth = dateTime.plusMonths(timeContinue); //加上月份
        String repayTime = dateTimePlusOneMonth.toString(); //转换成字符串

        repayTime = repayTime.substring(0, 19);
        repayTime = repayTime.replace('T', ' ');

        loanUser.setEndDate(repayTime);// 还款期限

        loanUser.setInterest(loanUser.getBalance() * loanUser.getLoanRate() + loanUser.getBalance());// 总还款利息

        loanUser.setProductStatus(4);// 设置贷款状态为4

        loanService.addUserAndLoan(loanUser);
        return "success";
    }

    //更新update：更新贷款项目
    @PutMapping("/update")
    public Result update(@RequestBody @Validated LoanProduct loanProduct) {
        loanService.update(loanProduct);
        return Result.success();
    }

    //更新update：更新用户-贷款表
    @PutMapping("/updateUP")
    public Result updateUP(@RequestBody @Validated LoanUser loanUser) {
        loanService.updateUP(loanUser);
        return Result.success();
    }

    //更新update：实现假删除
    @PutMapping("/delete")
    public Result delete(@RequestBody @Validated LoanProduct loanProduct) {
        loanProduct.setLoanStatus(2);
        loanService.delete(loanProduct);
        return Result.success();
    }

}
